package com.example.studyPlatform.kit;

import org.springframework.context.ApplicationContext;
import org.springframework.context.expression.BeanFactoryAccessor;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class Parser {
    ExpressionParser parser = new SpelExpressionParser();
    BeanFactoryAccessor beanFactoryAccessor=new BeanFactoryAccessor();
    TemplateParserContext template=new TemplateParserContext();
    ApplicationContext applicationContext;

    public Parser(ApplicationContext applicationContext) {
        this.applicationContext=applicationContext;
    }

    public <T> T parse(String expr, Class<T> clazz) {
        StandardEvaluationContext ctx = new StandardEvaluationContext(applicationContext);
        ctx.addPropertyAccessor(beanFactoryAccessor);
        return parser.parseExpression(expr, template).getValue(ctx, clazz);
    }

    public <T> T parse(String expr, Map<String, Object> context, Class<T> clazz) {
        StandardEvaluationContext ctx = new StandardEvaluationContext(applicationContext);
        ctx.addPropertyAccessor(beanFactoryAccessor);
        ctx.setVariables(context);
        return parser.parseExpression(expr, template).getValue(ctx, clazz);
    }
}
